const app = getApp()
const request = require('../../utils/request.js')

Page({
  data: {
    myMoney: 0,
    needMoney: 0.3,
    avata_url: "",
    nickName: "",
    hasUserAvar: false,
    isShowDialogModal: false
  },

  onShow: function () {
    console.log('请求服务器，获取我的钱！');
    let that = this;
    request.getMoney().then(res => {
    // console.log('lcsssss', res);
      this.setData({
        
        myMoney: (res.money / 10000).toFixed(3),
        needMoney: res.need_money / 10000
      });
    })

    if (app.globalData.userInfo) {
      console.log('user page 输出 userinof 看看', app.globalData.userInfo);
      this.setData({
        avata_url: app.globalData.userInfo.avatarUrl,
        nickName: this.nickNameToFixedLength(app.globalData.userInfo.nickName),
        hasUserAvar: true
      })
    } else {
      wx.getSetting({
        success(res) {
          if (res.authSetting["scope.userInfo"]) {
            wx.getUserInfo({
              success(res) {
                app.globalData.userInfo = res.userInfo
              }
            })
            that.setData({
              avata_url: app.globalData.userInfo.avatarUrl,
              nickName: this.nickNameToFixedLength(app.globalData.userInfo.nickName),
              hasUserAvar: true
            })
          } else {
            that.setData({
              avata_url: "/images/ava_default_2.png",
              nickName: "此用户暂无昵称",
              hasUserAvar: false
            })
          }
        }
      })
    }

    // 若 hasUserAvar 还是false则
    if(!this.data.hasUserAvar) {
      this.setData({
        isShowDialogModal: true
      })
    }else{
      this.setData({
        isShowDialogModal: false
      })
    }
  },

  withdraw: function() {
    console.log("立即提现！")
    wx.navigateTo({
      url: '../withdraw/withdraw?myMoney=' + this.data.myMoney + '&needMoney=' + this.data.needMoney
    })
  },

  stepLog: function() {
    console.log('步数记录');
    wx.navigateTo({
      url: '../stepLog/stepLog'
    })
  },


  // share
  onShareAppMessage: function(res) {
    if (res.from === 'button') {
      let url = "/pages/index/index?from_open_id=" + this.data.myOpenId
      let title = app.globalData.userInfo.nickName + "@你，【运动步数能赚钱】你还不知道吗？"
      return {
        title: title,
        imageUrl: "/images/publicize_3.jpg",
        path: url,
      }
    }
  },

  getUserInfo: function(e) {
    console.log("我的请求用户数据")
    this.setData({
      isShowDialogModal: false
    })

    if (e.detail.userInfo) {
      app.globalData.userInfo = e.detail.userInfo
      this.setData({
        avata_url: app.globalData.userInfo.avatarUrl,
        nickName: this.nickNameToFixedLength(app.globalData.userInfo.nickName),
        hasUserAvar: true,
      })
    }
  },

  //nickNameToFixedLength
  nickNameToFixedLength: function(nickName){
      if(nickName.length > 5){
        return nickName.substring(0, 5)+'...'
      }else{
        return nickName
      }
  }

})